import React, { useEffect, useState } from 'react'
import styles from './index.module.less'
import cm from 'classnames'
import { createRoot } from 'react-dom/client'

const getIcon = (type) => {
  const obj = {
    success: '/images/success-icon.png',
    error: '/images/error-icon.png',
  }
  return obj[type]
}

const Index = (props) => {
  const { type = '', content = '', onClose } = props
  const [closed, setClosed] = useState(false)
  const messageClass = cm(styles.message, styles[type], { [styles.closed]: closed })
  const close = () => {
    setClosed(true)
    setTimeout(() => {
      onClose()
    }, 300)
  }
  useEffect(() => {
    const t = setTimeout(close, 2000)
    return () => {
      t && clearTimeout(t)
    }
  }, [])
  return (
    <div className={messageClass}>
      {['success', 'error'].includes(type) ? <img src={getIcon(type)} alt="" className={styles['message-icon']} /> : ''}
      <div className={styles['message-content']}>{content}</div>
    </div>
  )
}

const getContainer = () => {
  const root = document.querySelector('#toast-root')
  return root
}

const _message = (type) => (content) => {
  const messageRoot = getContainer()
  const _dom = document.createElement('div')
  messageRoot.insertBefore(_dom, messageRoot.firstChild)

  const handleClose = () => {
    root.unmount()
    _dom.remove()
  }
  const root = createRoot(_dom)
  root.render(<Index type={type} content={content} onClose={handleClose} />)
}

const success = _message('success')
const error = _message('error')
const normal = _message('normal')
const Message = {
  success,
  error,
  normal,
}

export default Message
